package messageMeTransfer.connection;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Stack;

import messageMeTransfer.interfaces.IListener;
import messageMeTransfer.interfaces.IPackage;
import messageMeTransfer.utilities.PackageReciever;


public class ClientConnection implements IListener{

	private String IP = "localhost";
	private int PORT = 4489;
	
	private boolean connected = false;
	private Socket socket = null;

	private ObjectInputStream objectInputStream = null;
	private ObjectOutputStream objectOutputStream = null;
	
	private Stack<IPackage> recievedPackages = null;

	public ClientConnection() {
		this.establishConnection();
		this.initializeIO();
	}

	public boolean isConnected() {
		return this.connected;
	}

	public void send(IPackage iPackage) {
		try {
			this.objectOutputStream.writeObject(iPackage);
			this.objectOutputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public IPackage recieve() {
		IPackage iPackage = this.recievedPackages.firstElement();
		if(iPackage != null)
			this.recievedPackages.remove(iPackage);
		return iPackage;
	}

	private void establishConnection() {
		try {
			this.socket = new Socket(this.IP, this.PORT);
			if(socket != null)
			{
				this.connected = true;
				this.recievedPackages = new Stack<>();
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	private void initializeIO() {
		try {
			this.objectOutputStream = new ObjectOutputStream(
					this.socket.getOutputStream());
			objectOutputStream.flush();
			
			this.objectInputStream = new ObjectInputStream(
					this.socket.getInputStream());
			
			PackageReciever reader = new PackageReciever(this.objectInputStream);
			reader.addListener(this);
			reader.start();			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private void closeConnection() {
		try {
			this.objectInputStream.close();
			this.objectOutputStream.close();
			this.socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void packageRecieved(IPackage iPackage) {	
		this.recievedPackages.push(iPackage);
	}
}
